package com.example.elm.Public

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.common.BaiduMapSDKException
import com.baidu.mapapi.map.MapStatus
import com.baidu.mapapi.map.MapStatusUpdate
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MyLocationConfiguration
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.GeoCodeResult
import com.baidu.mapapi.search.geocode.GeoCoder
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult
import com.example.elm.Public.ui.theme.ElmTheme
import com.example.elm.databinding.AddressAddBinding
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class AddAddressActivity : ComponentActivity() {
    private lateinit var binding: AddressAddBinding
    private  lateinit  var locationClient:LocationClient
    private val server_ip = MyApplication.serverIp
    private  var maxIdA = MyApplication.maxIdA
    lateinit var geoCoder: GeoCoder
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //是否同意隐私政策，默认为false
        SDKInitializer.setAgreePrivacy(applicationContext, true)
        LocationClient.setAgreePrivacy(true)

        try {
            // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
            SDKInitializer.initialize(applicationContext)
            //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
            //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
            SDKInitializer.setCoordType(CoordType.BD09LL);
        } catch (e: BaiduMapSDKException) {
        }

        binding = AddressAddBinding.inflate(layoutInflater)
        setContentView(binding.root)

        getPermission()
        // 初始化定位
        initLocationClient()
        binding.mapView.map.isMyLocationEnabled = true // 开启地图的定位图层

        binding.btnAddAddress.setOnClickListener {
            val address = binding.etAddress.text.toString() + binding.etAddress2.text.toString()
            val username = binding.etUserName.text.toString()
            val user_phone = binding.etUserPhone.text.toString()
            maxIdA = maxIdA + 1
            val AddressData = AddressInfo(address, username, user_phone, 0, maxIdA)
            MyApplication.maxIdA = maxIdA
            if (address.isNotEmpty() && username.isNotEmpty() && user_phone.isNotEmpty()){
                addAddressPost(AddressData)
            } else{
                Toast.makeText(this, "请将地址信息填写完整", Toast.LENGTH_SHORT).show()
            }
            finish()
        }

        // 设置按钮点击事件，保存修改后的数据并返回
        binding.btnBack.setOnClickListener {
            finish()
        }

    }

    // 新增数据（post附加数据）
    fun addAddressPost(addressInfo: AddressInfo){
        val add_address_jsp = "http://$server_ip:8080/Address/add_Address.jsp"
        thread {
            var connection : HttpURLConnection ? = null
            try {
                val response = StringBuilder()
                val url = URL(add_address_jsp)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000 //  连接 超时
                connection.readTimeout = 8000 // read 超时时间
                connection.requestMethod = "POST"
                connection.setRequestProperty("Accept-Charset", "UTF-8")
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                val output = DataOutputStream(connection.outputStream)
                val paraStr = "&address=${addressInfo.address}&username=${addressInfo.name}&user_phone=${addressInfo.user_phone}&chosen=${addressInfo.chosen}&id=${addressInfo.id}"
                Log.d("chosen", "${addressInfo.chosen}")
                output.write(paraStr.toByteArray())
                val input = connection.inputStream
                //  读取输入流，类似与文件流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())
            }
            catch (e: Exception){
                e.printStackTrace()
            }
            finally {
                connection?.disconnect()
            }
        }
    }
    fun showResponse(response:String){
        runOnUiThread{
            Toast.makeText(this, response,Toast.LENGTH_SHORT).show()
        }

    }

    fun initLocationClient(){
        // 初始化定位客户端
        locationClient = LocationClient(applicationContext)

        //通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.openGps = true// 打开gps
        option.setCoorType("bd09ll") // 设置坐标类型
        option.setScanSpan(3000)
        //设置locationClientOption
        locationClient.locOption = option

        locationClient.registerLocationListener(MyLocationListener())
        locationClient.start()

        val map = binding.mapView.map
        // 设置地图中心点
        val latLng: LatLng = LatLng(30.255 , 119.7299)
        // 获取地图的 UI 设置
        val uiSettings = map.uiSettings
        // 禁用旋转手势（防止地图方向改变）
        uiSettings.isRotateGesturesEnabled = false
        // 设置地图状态（包括中心点和缩放级别）
        val mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(
            MapStatus.Builder()
                .target(latLng) // 设置地图中心点
                .zoom(16.0f)    // 设置缩放级别（数值越大显示越详细）
                .rotate(0.0f)   // 设置地图旋转角度为 0 度
                .build()
        )
        // 更新地图状态
        map.animateMapStatus(mapStatusUpdate)

        // 设置定位模式为跟随模式
        val locationConfiguration = MyLocationConfiguration(
            MyLocationConfiguration.LocationMode.NORMAL, // 跟随模式
            true, // 显示方向
            null // 使用默认定位图标
        )
        map.setMyLocationConfiguration(locationConfiguration)

        // 初始化 GeoCoder 反地理编码
        geoCoder = GeoCoder.newInstance()
        geoCoder.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {
            override fun onGetGeoCodeResult(result: GeoCodeResult?) {
                // 此处无需处理正地理编码
            }
            override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {
                Log.e("GeoCoder", "${result}")
                if (result == null) {
                    // 地址解析失败
                    binding.etAddress.hint = "获取地址失败"
                    return
                } else if (result.error != SearchResult.ERRORNO.NO_ERROR) {
                    binding.etAddress.hint = "无法获取当前位置的地址"
                    Log.e("GeoCoderDebug", "ReverseGeoCode Failed: ${result?.error}")
                    return
                }
                // 获取地址信息
                val address = result.address // 完整地址
                val sematicDescription = result.sematicDescription // 语义化地址（包括街道和门牌号）

                // 如果有语义化描述（sematicDescription），则显示它
                if (!sematicDescription.isNullOrEmpty()) {
                    //binding.etAddress.hint = sematicDescription
                    binding.etAddress.setText(sematicDescription.toString())
                } else {
                    // 如果没有语义化描述，显示完整地址
                    binding.etAddress.hint = address
                }
//                binding.etAddress.hint = address
            }
        })
    }

    // 定位监听器
    private inner class MyLocationListener: BDLocationListener {
        override fun onReceiveLocation(location: BDLocation?) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || binding.mapView == null) {
                return
            }
            // 创建地图坐标对象
            val latLng = LatLng(location.latitude, location. longitude)
            Log.d("LocationDebug", "Latitude: ${location.latitude}, Longitude: ${location.longitude}")
            // 更新地图中心点
            val mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng)
            binding.mapView.map.animateMapStatus(mapStatusUpdate) // 平滑移动到定位点

            val locData = MyLocationData.Builder()
                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.direction)
                .latitude(location.latitude)
                .longitude(location.longitude)
                .build()
            binding.mapView.map.setMyLocationData(locData)
            // position: 位置
            Log.e("Location", "${location?.longitude}--${location?.latitude}")
            //反地址编码
            geoCoder.reverseGeoCode(
                ReverseGeoCodeOption()
                    .location(latLng)
//                    .radius(100)
            )
        }
    }
    // 申请权限
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if(grantResults.isNotEmpty() ){
                    // 授权列表不为空
                    for(result in grantResults){
                        if(result != PackageManager.PERMISSION_GRANTED){
                            // 只有有一个未授权，则授权失败
                            Log.e("PermissionsResult", "授权失败")
                            return
                        }
                    }
                    // 执行到这一步，则成功
                    Log.e("PermissionsResult", "授权成功")
                }
            }
        }
    }
    // 获取权限
    private fun getPermission(){
        // 定义一个权限列表；只要有一个权限未通过，则权限不对
        val permissionList = ArrayList<String>()
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }


        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }

        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.ACCESS_WIFI_STATE)
        }

        // 如果权限列表不为空，则需要授权
        if( !permissionList.isEmpty() ){
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 2)
        }
        else{
            Log.e("getPermissions()", "权限通过")

        }

    }
    override fun onDestroy() {
        super.onDestroy()
        locationClient.unRegisterLocationListener(MyLocationListener()) // 取消监听
        locationClient.stop()
        binding.mapView.onDestroy()
        geoCoder.destroy()
    }

    override fun onPause() {
        super.onPause()
        binding.mapView.onPause()
    }

    override fun onResume() {
        super.onResume()
        binding.mapView.onResume()
    }
}

@Composable
fun Greeting3(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview3() {
    ElmTheme {
        Greeting3("Android")
    }
}